# -*- coding: utf-8 -*-
# 标准库导入
import sys
import os

# 第三方库导入
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem,
    QHeaderView, QMessageBox, QStackedWidget, QComboBox, QFormLayout,
    QDialog, QDialogButtonBox, QStyleFactory, QGraphicsDropShadowEffect,
    QSizePolicy  # 添加尺寸策略类
)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QColor, QDoubleValidator, QIntValidator
from tqsdk import TqApi, TqAuth, TqAccount, TqSim

# 本地模块导入
from db_manager import (
    connect_db,
    get_all_products,
    insert_product,
    update_product,
    delete_product,
    get_monitored_products,
    delete_product_by_name,
    get_product_by_id
)

class CapitalManager(QMainWindow):
    update_signal = pyqtSignal(str)
    connection_signal = pyqtSignal(str, bool)

    def _connect_thread(self):
        try:
            # 修正经纪商代码为官方格式（关键修复）
            self.tq_account = TqAccount("H徽商期货", "155831", "alibaba999")  
            self.api = TqApi(account=self.tq_account,
                           auth=TqAuth("szlwy68", "alibaba999"),
                           _stock=False)
            self.macc=self.api.get_account()
            print("已经成功连接天勤账户")
            print("当前账户可用资金：",self.macc.available)
            
            # 修正f-string语法错误
            self.update_signal.emit(f"{self.macc.available:.2f}")  # 新增
            
            # 发射连接成功信号
            self.connection_signal.emit("已连接 (点击断开)", True)
            self.update_capital()  # 启动资金更新线程
            
        except Exception as e:
            self.connection_signal.emit(f"连接失败: {str(e)}", False)

    def handle_connection(self, text, success):
        """处理连接状态更新"""
        self.connect_btn.setText(text)
        self.connect_btn.setEnabled(True)
        if success:
            # 断开原有连接并绑定断开方法
            try:
                self.connect_btn.clicked.disconnect()
            except TypeError:
                pass
            self.connect_btn.clicked.connect(lambda: self.disconnect_tq())
            QApplication.processEvents()
            # 删除下面这行已移除的方法调用
            # self.update_capital()  # <<< 这行需要删除
        else:
            # 重新绑定连接方法（关键修复）
            try:
                self.connect_btn.clicked.disconnect()
            except TypeError:
                pass
            self.connect_btn.clicked.connect(self.connect_tq)

    def connect_tq(self):
        """天勤账户连接主方法"""
        try:
            self.connect_btn.setEnabled(False)
            self.connect_btn.setText("连接中...")
            
            from threading import Thread
            Thread(target=self._connect_thread, daemon=True).start()
            
        except Exception as e:
            self.connect_btn.setEnabled(True)
            QMessageBox.critical(self, "错误", f"启动连接失败: {str(e)}")

    def disconnect_tq(self):  # 新增断开连接方法
        """断开天勤账户连接"""
        try:
            if self.api:
                self.api.close()
                self.api = None
                self.tq_account = None
                self.connect_btn.setText("连接天勤账户")
                self.capital_input.clear()
                QMessageBox.information(self, "断开成功", "已断开天勤账户连接")
                
                # 重新绑定连接方法
                self.connect_btn.clicked.disconnect()
                self.connect_btn.clicked.connect(self.connect_tq)
                
        except Exception as e:
            QMessageBox.critical(self, "断开错误", f"断开连接时发生错误: {str(e)}")

    def closeEvent(self, event): 
        self.disconnect_tq()
        event.accept()

    def _connect_thread(self):
        try:
            self.tq_account = TqAccount("H徽商期货", "155831", "alibaba999")  
            self.api = TqApi(account=self.tq_account,
                           auth=TqAuth("szlwy68", "alibaba999"),
                           _stock=False)
            
            self.macc=self.api.get_account()
            print("已经成功连接天勤账户")
            print("当前账户可用资金：",self.macc.available)
            
            self.update_signal.emit(f"{self.macc.available:.2f}") 
            self.connection_signal.emit("已连接 (点击断开)", True)
            
        except Exception as e:
            self.connection_signal.emit(f"连接失败: {str(e)}", False)

    def __init__(self):
        super().__init__()
        self.init_data()  # 初始化数据必须在最前面
        self.init_ui()
        self.setup_connections()
        self._init_help_ui()  # 确保帮助页面初始化被调用
        self.setWindowTitle("资金管理系统")
        self.resize(1200, 800)
        self.handle_page_change(0)

    # 添加 init_data 方法定义（必须位于类内部）
    def init_data(self):
        """初始化业务数据"""
        self.products = [
            {'name': '螺纹钢2501', 'exchange_code': 'SHFE.rb2501', 'margin': 5000, 'stoploss': 50, 'multiplier': 10},
            {'name': '棕榈油2509', 'exchange_code': 'DCE.p2509', 'margin': 6000, 'stoploss': 80, 'multiplier': 10},
            {'name': '沪铜2409', 'exchange_code': 'SHFE.cu2409', 'margin': 35000, 'stoploss': 200, 'multiplier': 5},
            {'name': '沪深300', 'exchange_code': 'CFFEX.IF2409', 'margin': 120000, 'stoploss': 30, 'multiplier': 300},
            {'name': '黄金2410', 'exchange_code': 'SHFE.au2410', 'margin': 40000, 'stoploss': 2, 'multiplier': 1000},
            {'name': '原油2409', 'exchange_code': 'INE.sc2409', 'margin': 80000, 'stoploss': 10, 'multiplier': 100},
            {'name': '豆粕2501', 'exchange_code': 'DCE.m2501', 'margin': 4500, 'stoploss': 40, 'multiplier': 10},
            {'name': 'PTA2501', 'exchange_code': 'CZCE.TA2501', 'margin': 3500, 'stoploss': 60, 'multiplier': 5},
            {'name': '玻璃2501', 'exchange_code': 'CZCE.FG2501', 'margin': 3000, 'stoploss': 30, 'multiplier': 20},
            {'name': '白糖2501', 'exchange_code': 'CZCE.SR2501', 'margin': 4000, 'stoploss': 40, 'multiplier': 10}
        ]
        self.api = None
        self.tq_account = None

    def init_ui(self):
        # ==== 主布局修复 ====
        main_widget = QWidget()
        main_h_layout = QHBoxLayout(main_widget)
        
        # ==== 左侧面板 ====
        side_panel = QWidget()
        side_layout = QVBoxLayout(side_panel)  # 只保留一次布局初始化
        
        # +++ 更新后的按钮配置 +++
        self.btn_calculate = QPushButton("计算下单量")
        self.btn_order = QPushButton("下单")
        self.btn_set_sl = QPushButton("品种管理")  # 修改按钮文本
        self.btn_auto_sl = QPushButton("启动自动止盈止损")
        self.btn_sl_params = QPushButton("帮助中心")
        
        # 设置按钮属性
        button_group = [
            self.btn_calculate, 
            self.btn_order,
            self.btn_set_sl,
            self.btn_auto_sl,
            self.btn_sl_params
        ]
        for btn in button_group:
            btn.setCheckable(True)
            btn.setMinimumHeight(40)
            btn.setMinimumWidth(200)
            side_layout.addWidget(btn)  # 直接在此处添加按钮
            
        side_layout.addStretch()
        
        # ==== 右侧堆叠窗口 ====
        self.stacked_widget = QStackedWidget()
        self._init_capital_ui()  # 页面0
        self.init_order_ui()     # 页面1
        
        # 修改页面2初始化方式（关键修复）
        self.stacked_widget.addWidget(self._init_product_management_ui())  # 页面2（品种管理）
        self.stacked_widget.addWidget(QWidget())  # 页面3（自动止盈止损）
        self.stacked_widget.addWidget(QWidget())  # 页面4（止盈止损参数）
        
        # 组合布局
        main_h_layout.addWidget(side_panel)
        main_h_layout.addWidget(self.stacked_widget, stretch=1)
        self.setCentralWidget(main_widget)

    def setup_connections(self):
        """连接信号与槽函数"""
        # 连接所有侧边栏按钮
        self.btn_calculate.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(0))  # 页面0
        self.btn_order.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(1))      # 页面1
        self.btn_set_sl.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(2))     # 页面2
        self.btn_auto_sl.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(3))    # 页面3
        self.btn_sl_params.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(4)) # 页面4
        
        # 连接账户按钮
        self.connect_btn.clicked.connect(self.connect_tq)
        
        # 连接更新信号
        self.update_signal.connect(lambda x: self.capital_input.setText(x))
        self.connection_signal.connect(self.handle_connection)
        
        # 页面切换处理
        self.stacked_widget.currentChanged.connect(self.handle_page_change)


    def handle_page_change(self, index):
        """处理页面切换时的按钮样式"""
        # 所有侧边栏按钮列表
        buttons = [
            self.btn_calculate,    # 0
            self.btn_order,        # 1
            self.btn_set_sl,       # 2
            self.btn_auto_sl,      # 3
            self.btn_sl_params     # 4
        ]
        
        # 更新所有按钮状态和样式
        for i, btn in enumerate(buttons):
            is_active = (i == index)
            btn.setChecked(is_active)
            
            btn.setStyleSheet(f"""
                QPushButton {{
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 {'#f0f8ff' if is_active else '#f5f5f5'}, 
                        stop:1 {'#c6e2ff' if is_active else '#e0e0e0'});
                    color: {'#2196F3' if is_active else '#666'};
                    font-weight: {'bold' if is_active else 'normal'};
                    border: 1px solid {'#90caf9' if is_active else '#bdbdbd'};
                    border-radius: 4px;
                    padding: 10px;
                    margin: 2px;
                    border-bottom: 2px solid {'rgba(33,150,243,0.3)' if is_active else 'rgba(0,0,0,0.1)'};
                }}
                QPushButton:hover {{
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 {'#e3f2fd' if is_active else '#eee'}, 
                        stop:1 {'#b3d4fc' if is_active else '#d5d5d5'});
                }}
                QPushButton:pressed {{
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 {'#bbdefb' if is_active else '#e0e0e0'}, 
                        stop:1 {'#90caf9' if is_active else '#bdbdbd'});
                    border-top: 2px solid rgba(0,0,0,0.1);
                    border-bottom: 0px;
                }}
            """)




    def _init_capital_ui(self):
        """资金管理界面初始化"""
        capital_widget = QWidget()
        layout = QVBoxLayout(capital_widget)
        layout.setContentsMargins(15, 15, 15, 15)
        
        # 恢复资金管理界面原有的UI组件
        self.connect_btn = QPushButton("连接天勤账户")
        self.connect_btn.clicked.connect(self.connect_tq)
        layout.addWidget(self.connect_btn)
        
        # 输入区域
        input_layout = QHBoxLayout()
        self.capital_input = QLineEdit()
        self.capital_input.setPlaceholderText("正在获取账户资金...")
        self.capital_input.setReadOnly(True)
        input_layout.addWidget(QLabel("账户可用资金:"))
        input_layout.addWidget(self.capital_input)
        
        self.risk_input = QLineEdit()
        self.risk_input.setPlaceholderText("输入风险比例（%）")
        self.risk_input.setText("20")
        input_layout.addWidget(QLabel("风险比例:"))
        input_layout.addWidget(self.risk_input)
        layout.addLayout(input_layout)
        
        # 计算按钮
        self.calc_btn = QPushButton("计算下单量")
        self.calc_btn.clicked.connect(self.calculate)
        layout.addWidget(self.calc_btn)
        
        # 表格
        self.table = QTableWidget()
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(["品种", "保证金", "止损金额", "建议开仓量", "最大开仓量"])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.table)

        # +++ 新增公式说明 +++
        formula_label = QLabel("""
            <div style='margin:15px 0; color:#666; font-size:12px;'>
                <b>计算公式说明：</b>
                <ul>
                    <li>风险资金 = 账户资金 × 风险比例</li>
                    <li>建议开仓量 = 风险资金 ÷ (保证金 × 3)</li>
                    <li>最大开仓量 = 风险资金 ÷ 保证金</li>
                    <li>止损金额 = 止损点数 × 合约乘数 × 价格单位</li>
                </ul>
                <div style='color:#2196F3;'>注：建议开仓量采用1/3仓位原则，最大开仓量表示当前风险承受下的极限仓位</div>
            </div>
        """)
        formula_label.setWordWrap(True)
        layout.addWidget(formula_label)

        self.stacked_widget.addWidget(capital_widget)


    def calculate(self):  
        """执行资金计算逻辑"""
        try:
            # 获取输入值
            risk_percent = float(self.risk_input.text())
            capital = float(self.capital_input.text()) if self.capital_input.text() else 0
            
            if risk_percent <= 0 or risk_percent > 100:
                raise ValueError("风险比例需在 0-100% 之间")
                
            # 清空表格
            self.table.setRowCount(0)
            
            # 计算每个品种的开仓量
            for product in self.products:
                max_lots = (capital * risk_percent / 100) / product['margin']
                suggested_lots = int(max_lots // 3)
                
                # 添加表格行
                row = self.table.rowCount()
                self.table.insertRow(row)
                
                # 填充数据
                self.table.setItem(row, 0, QTableWidgetItem(product['name']))
                self.table.setItem(row, 1, QTableWidgetItem(str(product['margin'])))
                self.table.setItem(row, 2, QTableWidgetItem(str(product['stoploss'])))
                self.table.setItem(row, 3, QTableWidgetItem(str(suggested_lots)))
                self.table.setItem(row, 4, QTableWidgetItem(f"{max_lots:.1f}"))
                
        except ValueError as e:
            QMessageBox.warning(self, "输入错误", str(e))
        except Exception as e:
            QMessageBox.critical(self, "计算错误", f"发生未知错误: {str(e)}")


    def init_order_ui(self):  
        """订单页面初始化"""
        order_widget = QWidget()
        layout = QVBoxLayout(order_widget)
        layout.setContentsMargins(15, 15, 15, 15)
        
        # 从数据库获取监控品种
        conn = connect_db()
        monitored_products = []
        if conn:
            monitored_products = get_monitored_products(conn)  # 现在可以正确调用
            conn.close()
        
        # 添加订单界面基础组件
        self.symbol_combo = QComboBox()
        self.symbol_combo.addItems([p[1] for p in monitored_products])  # 使用数据库中的名称
        
        self.quantity_input = QLineEdit("1")  # 设置默认数量为1
        
        # 创建三个操作按钮
        btn_layout = QHBoxLayout()
        buy_btn = QPushButton("买进")
        sell_btn = QPushButton("卖出") 
        close_btn = QPushButton("平仓")
        
        # 绑定不同操作类型
        buy_btn.clicked.connect(lambda: self.submit_order("BUY", "OPEN"))
        sell_btn.clicked.connect(lambda: self.submit_order("SELL", "OPEN"))
        close_btn.clicked.connect(lambda: self.submit_order("", "CLOSE"))
        
        btn_layout.addWidget(buy_btn)
        btn_layout.addWidget(sell_btn)
        btn_layout.addWidget(close_btn)
        
        form_layout = QFormLayout()
        form_layout.addRow("选择品种:", self.symbol_combo)
        form_layout.addRow("下单数量:", self.quantity_input)
        
        layout.addLayout(form_layout)
        layout.addLayout(btn_layout)
        layout.addStretch()
        
        self.stacked_widget.insertWidget(1, order_widget)

    def submit_order(self, direction, offset):
        """处理订单提交"""
        try:
            # 获取选择的交易所代码
            conn = connect_db()
            monitored_products = get_monitored_products(conn) if conn else []
            selected = monitored_products[self.symbol_combo.currentIndex()]
            exchange_code = selected[2]  # 获取交易所代码
            
            quantity = int(self.quantity_input.text())
            
            if not self.api:
                raise RuntimeError("请先连接天勤账户")
                
            # 特殊处理平仓指令
            if offset == "CLOSE":
                direction = "CLOSE_ALL"  # 自定义平仓指令
                
            # 创建订单（需根据实际API调整）
            order = self.api.insert_order(
                symbol=exchange_code,
                direction=direction if offset != "CLOSE" else "SELL",
                offset=offset,
                volume=quantity
            )
            
            action = "买进" if direction == "BUY" else "卖出"
            action = "平仓" if offset == "CLOSE" else action
            QMessageBox.information(self, "下单成功", f"已提交{exchange_code} {quantity}手{action}指令")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"操作失败: {str(e)}")


    def _init_product_management_ui(self):
        """品种管理页面初始化"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        layout.setContentsMargins(10, 10, 10, 10)  # 减小边距
        
        # 创建表格控件
        self.product_table = QTableWidget()
        self.product_table.setColumnCount(6)
        self.product_table.setHorizontalHeaderLabels(["品种名称", "交易所代码", "保证金", "止损点数", "止盈点数", "是否监控"])
        self.product_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 自动拉伸列宽
        self.product_table.horizontalHeader().setDefaultAlignment(Qt.AlignLeft)  # 新增：表头左对齐
        self.product_table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)  # 新增：尺寸策略
        
        # 设置表格样式
        self.product_table.verticalHeader().setDefaultSectionSize(30)  # 行高统一为30px
        self.product_table.setShowGrid(False)  # 隐藏网格线
        self.product_table.setAlternatingRowColors(True)  # 启用交替行颜色
        
        # 修改按钮组布局
        btn_layout = QHBoxLayout()
        # +++ 调整按钮顺序 +++
        refresh_btn = QPushButton("刷新")  # 先创建刷新按钮
        add_btn = QPushButton("添加品种")
        edit_btn = QPushButton("编辑品种")
        del_btn = QPushButton("删除品种")
        
        # 设置按钮属性
        for btn in [add_btn, edit_btn, del_btn]:
            btn.setMinimumWidth(100)
            btn.setMinimumHeight(30)
        
        # 绑定事件
        add_btn.clicked.connect(self._show_add_product_dialog)
        edit_btn.clicked.connect(self._show_edit_dialog)
        del_btn.clicked.connect(self._delete_selected_product)
        
        # 添加按钮到布局
        btn_layout.addWidget(refresh_btn)  # 第一个按钮
        btn_layout.addWidget(add_btn)
        btn_layout.addWidget(edit_btn)
        btn_layout.addWidget(del_btn)
        # --- 按钮创建结束 ---
        
        # 调整布局比例（按钮组:表格 = 1:9）
        layout.addLayout(btn_layout, stretch=1)
        layout.addWidget(self.product_table, stretch=9)  # 设置拉伸因子
        
        # 初始化表格数据
        self._refresh_product_table()
        return widget

    # 新增类方法定义（必须位于类内部）
    def _refresh_product_table(self):
        """刷新品种表格数据"""
        conn = connect_db()
        if conn:
            products = get_all_products(conn)
            self.product_table.setRowCount(len(products))
            
            for row, product in enumerate(products):
                self.product_table.setItem(row, 0, QTableWidgetItem(product[1]))
                self.product_table.setItem(row, 1, QTableWidgetItem(product[2]))
                self.product_table.setItem(row, 2, QTableWidgetItem(str(product[3])))
                self.product_table.setItem(row, 3, QTableWidgetItem(f"{product[4]:.1f}"))  # 止损显示1位小数
                self.product_table.setItem(row, 4, QTableWidgetItem(f"{product[5]:.1f}"))  # 止盈显示1位小数
                self.product_table.setItem(row, 5, QTableWidgetItem("是" if product[6] else "否"))
                self.product_table.item(row, 0).setData(Qt.UserRole, product[0])  # 存储数据库ID
            conn.close()

    def _show_add_product_dialog(self):
        """显示添加品种对话框"""
        dialog = QDialog(self)
        dialog.setWindowTitle("添加新品种")
        layout = QFormLayout(dialog)  # 创建新的布局
        
        # 创建输入控件
        name_edit = QLineEdit()
        code_edit = QLineEdit()
        margin_edit = QLineEdit()
        stoploss_edit = QLineEdit()
        takeprofit_edit = QLineEdit()
        monitor_combo = QComboBox()
        monitor_combo.addItems(["是", "否"])
        
        # 添加控件到布局
        layout.addRow("品种名称:", name_edit)
        layout.addRow("交易所代码:", code_edit)
        layout.addRow("保证金:", margin_edit)
        layout.addRow("止损点数:", stoploss_edit)
        layout.addRow("止盈点数:", takeprofit_edit)
        layout.addRow("是否监控:", monitor_combo)
        
        # 添加按钮
        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(lambda: self._save_new_product(
            dialog,
            name_edit.text(),
            code_edit.text(),
            margin_edit.text(),
            stoploss_edit.text(),
            takeprofit_edit.text(),
            monitor_combo.currentText()
        ))
        btn_box.rejected.connect(dialog.reject)
        
        layout.addWidget(btn_box)
        dialog.exec_()

    def _save_new_product(self, dialog, name, code, margin, stoploss, takeprofit, monitor):
        """保存新品种到数据库"""
        try:
            conn = connect_db()
            insert_product(conn, (
                name,
                code,
                float(margin),
                float(stoploss),   # 保持浮点转换
                float(takeprofit), # 修改为浮点转换
                1 if monitor == "是" else 0
            ))
            conn.commit()  # 确保提交
            conn.close()
            self._refresh_product_table()  # 刷新表格
            dialog.accept()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"添加失败: {str(e)}")
            if conn:  # 新增异常时关闭连接
                conn.close()

    def _show_edit_dialog(self):
        """显示编辑对话框（完整实现）"""
        selected_row = self.product_table.currentRow()
        if selected_row == -1:
            return
        
        # 获取原始数据
        product_id = self.product_table.item(selected_row, 0).data(Qt.UserRole)
        conn = connect_db()
        product = get_product_by_id(conn, product_id)
        conn.close()
        
        # 创建编辑对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("编辑品种")
        layout = QFormLayout(dialog)
        
        # 初始化输入框并填充数据（修复变量名错误）
        name_edit = QLineEdit(product[1])
        code_edit = QLineEdit(product[2])
        margin_edit = QLineEdit(str(product[3]))
        stoploss_edit = QLineEdit(f"{product[4]:.1f}")  # 格式化为1位小数
        takeprofit_edit = QLineEdit(f"{product[5]:.1f}")
        
        # 添加相同的验证器
        margin_edit.setValidator(QDoubleValidator())
        stoploss_edit.setValidator(QDoubleValidator())
        takeprofit_edit.setValidator(QDoubleValidator())
        monitor_check = QComboBox()
        monitor_check.addItems(["是", "否"])
        monitor_check.setCurrentIndex(0 if product[6] else 1)
        
        # 添加输入框到布局（修复乱码字段名）
        layout.addRow("品种名称:", name_edit)
        layout.addRow("交易所代码:", code_edit)
        layout.addRow("保证金:", margin_edit)
        layout.addRow("止损点数:", stoploss_edit)
        layout.addRow("止盈点数:", takeprofit_edit)
        layout.addRow("是否监控:", monitor_check)
        
        # 添加对话框按钮
        btn_box = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(lambda: self._update_product_data(
            dialog,
            product_id,
            name_edit.text(),
            code_edit.text(),
            margin_edit.text(),
            stoploss_edit.text(),
            takeprofit_edit.text(),
            monitor_check.currentText()
        ))
        btn_box.rejected.connect(dialog.reject)
        
        layout.addWidget(btn_box)
        dialog.exec_()

    def _update_product_data(self, dialog, product_id, name, code, margin, stoploss, takeprofit, monitor):
        """更新数据库中的品种信息"""
        try:
            conn = connect_db()
            updates = {
                'name': name,
                'exchange_code': code,
                'margin': float(margin),
                'stoploss': float(stoploss),
                'takeprofit': float(takeprofit),  # 修改为浮点类型
                'is_monitored': 1 if monitor == "是" else 0
            }
            # 执行更新操作（需要实现update_product函数）
            update_product(conn, product_id, updates)
            conn.commit()
            conn.close()
            self._refresh_product_table()
            dialog.accept()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"更新失败: {str(e)}")

    def _delete_selected_product(self):
        """删除选中品种（修复版）"""
        selected_row = self.product_table.currentRow()
        if selected_row == -1:
            return
        
        # 获取数据库ID（关键修复）
        product_id = self.product_table.item(selected_row, 0).data(Qt.UserRole)
        product_name = self.product_table.item(selected_row, 0).text()
        
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除 {product_name} 吗？",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            try:
                conn = connect_db()
                # 使用新的删除方法
                delete_product_by_name(conn, product_name)
                conn.commit()
                conn.close()
                self._refresh_product_table()
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败: {str(e)}")
    
    def _show_edit_dialog(self):
        """显示编辑对话框（完整实现）"""
        selected_row = self.product_table.currentRow()
        if selected_row == -1:
            return
        
        # 获取原始数据
        product_id = self.product_table.item(selected_row, 0).data(Qt.UserRole)
        conn = connect_db()
        product = get_product_by_id(conn, product_id)
        conn.close()
        
        # 创建编辑对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("编辑品种")
        layout = QFormLayout(dialog)
        
        # 初始化输入框并填充数据（修复变量名错误）
        name_edit = QLineEdit(product[1])
        code_edit = QLineEdit(product[2])
        margin_edit = QLineEdit(str(product[3]))
        stoploss_edit = QLineEdit(str(product[4]))
        takeprofit_edit = QLineEdit(str(product[5]))  # 修正后的正确变量名
        monitor_check = QComboBox()
        monitor_check.addItems(["是", "否"])
        monitor_check.setCurrentIndex(0 if product[6] else 1)
        
        # 添加输入框到布局（修复乱码字段名）
        layout.addRow("品种名称:", name_edit)
        layout.addRow("交易所代码:", code_edit)
        layout.addRow("保证金:", margin_edit)
        layout.addRow("止损点数:", stoploss_edit)
        layout.addRow("止盈点数:", takeprofit_edit)
        layout.addRow("是否监控:", monitor_check)
        
        # 添加对话框按钮
        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(lambda: self._save_edit(
            dialog, product_id, {
                'name': name_edit.text(),
                'exchange_code': code_edit.text(),
                'margin': margin_edit.text(),
                'stoploss': stoploss_edit.text(),
                'takeprofit': takeprofit_edit.text(),  # 修改字段名称
                'is_monitored': monitor_check.currentText()
            }
        ))
        btn_box.rejected.connect(dialog.reject)
        
        layout.addWidget(btn_box)
        dialog.exec_()
    
    def _save_edit(self, dialog, product_id, updates):
        """保存修改到数据库"""
        try:
            conn = connect_db()
            # 转换数据类型（修复字段类型）
            data = {
                'name': updates['name'],
                'exchange_code': updates['exchange_code'],
                'margin': float(updates['margin']),
                'stoploss': float(updates['stoploss']),  # 改为浮点转换
                'takeprofit': float(updates['takeprofit']),  
                'is_monitored': 1 if updates['is_monitored'] == "是" else 0
            }
            update_product(conn, product_id, data)
            conn.commit()
            conn.close()
            self._refresh_product_table()
            dialog.accept()
            QMessageBox.information(self, "成功", "修改已保存")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存失败: {str(e)}")

    def _init_help_ui(self):
        """帮助中心页面初始化"""
        help_widget = QWidget()
        main_layout = QVBoxLayout(help_widget)  # 改为垂直布局
        
        # 帮助文本部分
        text_widget = QWidget()  # 确保变量在此处定义
        text_layout = QVBoxLayout(text_widget)
        text_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        
        help_text = QLabel("""
            <h2 style="margin-left:10px;">帮助中心</h2>
            <div style="margin-left:20px;">
            <p>📌 使用指南：</p>
            <ul>
                <li>品种管理：添加/修改监控的期货品种参数</li>
                <li>自动止盈止损：设置自动化的交易策略</li>
                <li>账户连接：绑定天勤账户获取实时资金数据</li>
            </ul>
            <p>🆘 技术支持：QQ群：653552377</p>
            </div>
        """)
        help_text.setAlignment(Qt.AlignLeft)
        help_text.setWordWrap(True)
        text_layout.addWidget(help_text)  # 确保将文本添加到布局
        
        # 图片部分
        img_label = QLabel()
        pixmap = QPixmap("img/beauty02.png")
        if not pixmap.isNull():
            pixmap = pixmap.scaled(400, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            img_label.setPixmap(pixmap)
            img_label.setStyleSheet("""
                QLabel {
                    border-radius: 8px;
                    margin: 15px;
                    background: transparent;  /* 移除多余背景色 */
                }
            """)  # 简化样式表            
            # 阴影效果保持不变
            shadow = QGraphicsDropShadowEffect()
            shadow.setBlurRadius(20)
            shadow.setOffset(5, 5)
            shadow.setColor(QColor(0, 0, 0, 60))  # 现在可以正常使用 QColor
            img_label.setGraphicsEffect(shadow)
        else:
            img_label.setText("图片加载失败")
        
        # 组合布局（文字在上，图片在下）
        main_layout.addWidget(text_widget, stretch=1)
        main_layout.addWidget(img_label, alignment=Qt.AlignLeft)  # 修改对齐方式为左对齐
        
        # 调整图片容器的边距
        img_label.setContentsMargins(20, 0, 0, 20)  # 添加左部边距20px，底部边距20px
        
        self.stacked_widget.insertWidget(4, help_widget)

if __name__ == "__main__":
    # 移除重复的 os 导入（已合并到文件顶部）
    # 新增的禁用PNG警告设置保持不变
    os.environ["QT_LOGGING_RULES"] = "qt.png.warning=false"
    
    app = QApplication(sys.argv)
    # 修正后的样式设置（确保QStyleFactory已导入）
    app.setStyle(QStyleFactory.create("WindowsVista")) 
    app.setFont(QFont("微软雅黑", 9))
    app.setStyleSheet("""
        * {
            font-family: "微软雅黑", "Consolas";
        }
        QLineEdit, QTableWidget, QLabel {
            font: 10pt "Consolas", "微软雅黑";
        }
        QTableWidget {
            background-color: white;
            border: 1px solid #E0E0E0;
            margin-top: 10px;
        }
        QTableWidget::item {
            padding: 5px;
        }
        QLineEdit {
            min-height: 25px;
            padding: 2px 5px;
        }
        QTableWidget {
            min-width: 800px;  /* 新增最小宽度 */
        }
        QLineEdit {
            min-width: 150px;
        }
        QComboBox {
            min-width: 200px;
        }
    """)
    app.setWindowIcon(QIcon('app.png'))
    window = CapitalManager()
    window.show()
    sys.exit(app.exec_())